package com.java.simple.study.jvm.classloader;

import java.io.FileNotFoundException;

/**
 * @author zhoujunlin
 * @date 2022年05月15日 21:49
 * @desc
 */
public class CustomerClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] result = getClassFromCustomPath(name);
            if (result == null) {
                throw new FileNotFoundException();
            } else {
                //defineClass和findClass搭配使用
                return defineClass(name, result, 0, result.length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        throw new ClassNotFoundException();

    }

    /**
     * 自定义流的获取方式
     *
     * @param name
     * @return
     */
    private byte[] getClassFromCustomPath(String name) {
        // 从自定义路径加载指定类 细节略
        // 如果指定路径的字节码文件进行了加密  则需要在此方法中进行解密操作
        return null;
    }


    public static void main(String[] args) {
        try {
            CustomerClassLoader customerClassLoader = new CustomerClassLoader();
            Class<?> clazz = Class.forName("One", true, customerClassLoader);
            Object obj = clazz.newInstance();
            System.out.println(obj.getClass().getClassLoader());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
